package com.base.cn.platform.os.interceptor;

import com.base.cn.platform.os.common.md5.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.IntStream;

/**
 * 签名验证工具
 *
 * @author s.li
 * @date 2018/11/19
 */
@Component
@Slf4j
class SignCheck {
    private static String signName = "sign";
    private static String privateKey = "privateKey";

    /**
     * 验证私钥
     * @param request
     * @param oldPrivateKey 系统缓存的密钥
     * @return false验证失败，true验证成功
     */
    public boolean checkPrivateKey(HttpServletRequest request,String oldPrivateKey){
        String _privateKey = request.getParameter(privateKey);
        if(!_privateKey.equals(oldPrivateKey)){
            return false;
        }
        return true;
    }

    /**
     * 验证签名
     * @param request
     * @return false验证失败，true验证成功
     */
    public boolean signCheck(HttpServletRequest request){
        Enumeration<String> parameterNames = request.getParameterNames();
        TreeMap<String,String> treeMap = new TreeMap<>();
        while (parameterNames.hasMoreElements()){
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            treeMap.put(key,value);
        }
        String sign = treeMap.get(signName);
        treeMap.remove(signName);
        List<String> keyList = new ArrayList<>(treeMap.keySet());
        StringBuilder signContext = new StringBuilder();
        IntStream.range(0,keyList.size()).forEach(index->{
            String key = keyList.get(index);
            String value = treeMap.get(key);
            signContext.append(key).append("|").append(value);
            if(index < keyList.size() -1){
                signContext.append("|");
            }
        });
        String _sign = MD5.getMD5(signContext.toString());
        log.info("------------------------------签名明文内容："+signContext.toString());
        log.info("------------------------------ 平台加密的签名:"+_sign);
        log.info("------------------------------ 接收到的签名:"+sign);
        if(!_sign.equals(sign)){
            return false;
        }
        return true;
    }


}
